<?php

namespace app\modules\clinical\models;

use Yii;
use app\models\Helpers;
use app\models\HsptLabel;

/**
 * This is the model class for table "hspt_patient".
 *
 * @property integer $pk_id
 * @property string $pt_id
 * @property string $pt_name
 * @property string $pt_birth
 * @property integer $pt_sex
 * @property integer $pt_nation
 * @property integer $pt_marry
 * @property string $pt_native
 * @property string $pt_addr
 * @property integer $pt_edu
 * @property string $pt_vocation
 * @property string $pt_insu
 * @property integer $rel_relation1
 * @property string $rel_phone1
 * @property string $rel_email1
 * @property integer $rel_relation2
 * @property string $rel_phone2
 * @property string $rel_email2
 * @property string $crt_name
 * @property string $crt_date
 * @property integer $pt_fml
 * @property integer $pt_jinqin
 * @property string $pt_history
 * @property string $pt_disease
 * @property string $pt_age
 * @property string $pt_intro
 * @property string $isCooperate
 * @property string $pt_hsp
 * @property string $pt_dead
 * @property string $pt_label
 */
class Patient extends \yii\db\ActiveRecord
{
    public $dbs_id;
    public $dbs_time;
    public $med_id;
    public $pt_other_history;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'hspt_patient';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['pt_name', 'pt_birth'], 'required'],
            [['pt_birth'], 'match', 'pattern' => '/\d{4}-\d{2}-\d{2}/'],
            [['crt_date', 'update_at', 'pt_dead'], 'safe'],
            [['pt_sex', 'pt_nation', 'pt_marry', 'pt_edu', 'pt_insu', 'rel_relation1', 'rel_relation2', 'pt_fml', 'pt_jinqin', 'pt_age', 'isCooperate', 'pt_customary'], 'integer'],
            [['dna_id', 'pt_id', 'pt_name', 'pt_native', 'pt_intro', 'crt_name', 'update_name', 'pt_other_history'], 'string', 'max' => 20],
            [['pt_addr', 'pt_vocation', 'pt_disease', 'pt_label', 'pt_note'], 'string', 'max' => 255],
            [['rel_phone1', 'rel_phone2'], 'string', 'max' => 11],
            [['rel_email1', 'rel_email2', 'pt_hsp'], 'string', 'max' => 30],
            [['pt_history'], 'filter', 'filter' => function($array) {
                return is_array($array) ? implode("+", $array) : "";
            }],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'pt_id' => '病案号',
            'dna_id' => '分子号',
            'pt_name' => '姓名',
            'pt_birth' => '出生日期',
            'pt_sex' => '性别',
            'pt_nation' => '民族',
            'pt_marry' => '婚姻状况',
            'pt_native' => '籍贯',
            'pt_addr' => '详细通讯地址',
            'pt_edu' => '文化程度',
            'pt_vocation' => '职业',
            'pt_insu' => '医保',
            'rel_relation1' => '与患者关系1',
            'rel_phone1' => '联系电话1',
            'rel_email1' => '电子邮件1',
            'rel_relation2' => '与患者关系2',
            'rel_phone2' => '联系电话2',
            'rel_email2' => '电子邮件2',
            'crt_name' => '创建人',
            'crt_date' => '创建日期',
            'pt_fml' => '有无家族史',
            'pt_jinqin' => '父母是否近亲',
            'pt_history' => '既往史',
            'pt_disease' => '诊断',
            'pt_age' => '发病年龄',
            'pt_rel' => '亲属关系',
            'pt_intro' => '介绍人',
            'pt_label' => '标签',
            'isCooperate' => '配合程度',
            'pt_hsp' => '就诊医院',
            'pt_dead' => '是否死亡',
            'pt_note' => '备注',
            'pt_customary' => '惯用手',
            'update_name' => '修改人',
            'update_at' => '修改时间',

            'dbs_id' => 'DBS',
            'dbs_time' => 'DBS 时间',
            'med_id' => '药物对应PD表格',
        ];
    }

    public static function getParams($type = false, $code = false) {
        $params = [
            'nation' => ['1' => '汉族', '2' => '蒙古族', '3' => '回族', '4' => '藏族', '5' => '维吾尔族', '6' => '苗族', '7' => '彝族', '8' => '壮族', '9' => '布依族', '10' => '朝鲜族', '11' => '满族', '12' => '侗族', '13' => '瑶族', '14' => '白族', '15' => '土家族', '16' => '哈尼族', '17' => '哈萨克族', '18' => '傣族', '19' => '黎族', '20' => '傈僳族', '21' => '佤族', '22' => '畲族', '23' => '高山族', '24' => '拉祜族', '25' => '水族', '26' => '东乡族', '27' => '纳西族', '28' => '景颇族', '29' => '柯尔克孜族', '30' => '土族', '31' => '达斡尔族', '32' => '仫佬族', '33' => '羌族', '34' => '布朗族', '35' => '撒拉族', '36' => '毛难族', '37' => '仡佬族', '38' => '锡伯族', '39' => '阿昌族', '40' => '普米族', '41' => '塔吉克族', '42' => '怒族', '43' => '乌孜别克族', '44' => '俄罗斯族', '45' => '鄂温克族', '46' => '崩龙族', '47' => '保安族', '48' => '裕固族', '49' => '京族', '50' => '塔塔尔族', '51' => '独龙族', '52' => '鄂伦春族', '53' => '赫哲族', '54' => '门巴族', '55' => '珞巴族', '56' => '基诺族'],

            'edu' => ['0' => '小学及以下', '1' => '初中', '2' => '高中／中专', '3' => '大学及以上'],
            'marry' => ['0' => '未婚', '1' => '已婚', '2' => '离异', '3' => '丧偶'],
            'sex' => ['1' => '男', '0' => '女'],

            'history' => ['肺气肿或慢性支气管炎、哮喘', '运动神经元病', '心率不齐', '共济失调', '心肌梗塞、心绞痛', '癫痫', '其他类型心脏病', '高脂血症候', '高血压', '酒依赖或中毒', '肝硬化', '精神疾病', '肾脏疾病', '白内障', '糖尿病', '耳聋（需大声说话或用助听器）', '甲状腺功能减低', '前列腺肥大或小便不畅', '甲状腺功能亢进', '骨关节畸形（指、趾、脊柱、其他）', '恶性肿瘤、白血病', '脑外伤', '骨折*（股骨、上肢、其他）', '脑血管病（腔梗、血栓、出血、蛛网膜下出血）', '脑供血不足', '其他疾病'],

            'relation' => ['0' => '本人', '1' => '配偶', '2' => '父亲', '3' => '母亲', '4' => '女儿', '5' => '儿子', '6' => '哥哥', '7' => '姐姐', '8' => '弟弟', '9' => '妹妹', '10' => '其他亲属'],
            'disease' => ['PD', 'ET', 'ET-PD', 'FCMTE', 'SCA', 'HSP', 'PFBC', 'CMT', '其他'],
            'yesno' => ['1' => '是', '0' => '否'],
            'youwu' => ['1' => '有', '0' => '无'],
            'insurance' => ['0' => '省医保', '1' => '市医保', '2' => '农保', '3' => '外地医保', '4' => '职工医保', '5' => '自费'],
            'customary' => ['0' => '', '1' => '左利手', '2' => '右利手'],
        ];

        if ($code !== false) {
            return ($type) ? $params[$type][$code] : '';
        }

        return ($type) ? $params[$type] : [];
    }

    public function defaultValue()
    {
        $this->pt_fml = 0;
        $this->pt_insu = 5;
        $this->pt_jinqin = 0;
        $this->isCooperate = 1;
        $this->pt_dead = "1001-01-01";
    }

    public function beforeSave($insert)
    {
        if ($this->pt_age == '') $this->pt_age = 0;
        $this->pt_label = Helpers::clearStringForArray($this->pt_label);
        
        if(parent::beforeSave($insert)){
            if (!empty($this->pt_other_history)) {
                $this->pt_history .= "+'".$this->pt_other_history."'";
            }

            if($this->isNewRecord){
                $this->crt_date = date('y-m-d H:i:s');
                $this->crt_name = Yii::$app->user->identity->username;
            }else{
                $this->update_at = date('y-m-d H:i:s');
                $this->update_name = Yii::$app->user->identity->username;
            }
            return true;
        }else{

            return false;
        }
    }

    public function getGene()
    {
        return $this->hasOne(GeneInfo::className(), ['pt_id' => 'pk_id']);
    }

    static public function getHistory($data) {
        $history = explode("+", $data);
        $string = "";

        foreach ($history as $key) {
            if ($key == '25') continue;

            if (preg_match('/^[0-9]+$/', $key)) {
                $string .= self::getParams('history', intval($key)) . ", ";
            } else {
                $string .= str_replace("'", "", $key) . ", ";
            }
        }

        $string = substr($string, 0, strlen($string)-2);

        return $string;
    }

    static public function getLabel($data) {
        $ids = explode("+", $data);
        $string = "";

        $labels = HsptLabel::find()->where(['in', 'id', $ids])->all();
        foreach ($labels as $label) {
            $string .= $label->name.', ';
        }

        $string = substr($string, 0, strlen($string)-2);

        return $string;
    }

    public function getRelatives() {
        $list['0'] = '本人   '.Yii::$app->session->get('pt_name');

        $relation = $this->getRelations();

        $relatives = Patient::find(['pt_name', 'pt_sex'])->where(['in', 'pk_id', array_keys($relation)])->all();
        foreach ($relatives as $model) {
            $list[$model->pk_id] = self::getParams('relation', $relation[$model->pk_id]).'  '.$model->pt_name;
        }

        return $list;
    }

    public function getRelations()
    {
        $json = ($this->pt_rel != '') ? json_decode($this->pt_rel) : [];

        if (count($json) < 1) return ['rel'=>'', 'key'=>''];

        foreach ($json as $value) {
            $rel[$value->pt_id] = $value->rel;//rel's [pt_id => relation]
        }

        return $rel;
    }

    public function clearRadio()
    {
        //pt_disease
        if (!is_numeric($this->pt_disease) && $this->pt_disease != '') {
            $pt_disease_str = $this->pt_disease;
            $this->pt_disease = 8;
        } else {
          $pt_disease_str = "";
        }

        //pt_dead
        if ($this->pt_dead != "" && $this->pt_dead != '1001-01-01') {
            $pt_dead_str = $this->pt_dead;
            $this->pt_dead = 1;
        } else {
            $pt_dead_str = "";
        }

        //pt_age
        if ($this->pt_age == 0) $this->pt_age = '';

        return ['disease' => $pt_disease_str, 'dead' => $pt_dead_str];
    }

    //used on update
    public function clearCheckBox()
    {
        //pt_history
        $pt_history_str = '';

        if ($this->pt_history != '') {
            (!is_array($this->pt_history)) ? $this->pt_history = explode("+", $this->pt_history) : '';

            $pt_history_str = $this->pt_history[count($this->pt_history) - 1];
            if (preg_match('/^[0-9]+$/', $pt_history_str)) {
                $pt_history_str = '';
            } else {
                $pt_history_str = str_replace("'", "", $pt_history_str);
            }
        }

        return $pt_history_str;
    }
}
